import React, { Fragment } from 'react'
import './index.less'
import Tabs from '../../components/Tabs'
import http from 'libs/http'
import { downloadByObjectKey } from 'libs/utils'
import { Icon, Upload } from 'antd'
import { MediaPlayer, Dialog, NoData } from 'components'

export default class extends React.Component {
  state = {
    tabsData: [
      { courseType: 0, name: '全部课程', active: true },
      { courseType: 1, name: '龙英语', },
      { courseType: 3, name: '龙编程' },
    ],
    courseType: 0,
    recordList: [],
    loading: [],
    mediaShow: false,
    mediaTitle: '',
    mediaUrl: '',
  }

  componentDidMount() {
    this.getCourseTablesList()
  }

  // 获取直播课列表
  getCourseTablesList = () => {
    const { courseType } = this.state
    http.get('/student/course-table/listRecord', { courseType }).then(res => {
      console.log('录播课列表', res)
      this.setState({ recordList: res.data })
    })
  }

  // 全部课程、龙英语、龙编程之间切换
  changeTab = index => () => {
    const { tabsData } = this.state
    let courseType = 0
    tabsData.map((tab, i) => {
      if(index === i) {
        tab.active = true
        courseType = tab.courseType
      }else{
        tab.active = false
      }
    })
    this.setState({
      tabsData, courseType
    }, this.getCourseTablesList)
  }

  // 任务上传 
  uploadCourseTask = (i, j) => info => {
    const loading = this.state.loading;
    if (info.file.status === 'uploading') {
      loading[Number((i+1)+''+(j+1))] = true;
      this.setState({ loading });
      return;
    }
    if (info.file.status === 'done') {
      loading[Number((i+1)+''+(j+1))] = false;
      // _alert('作业已上传成功!');
      Dialog({
        message: '作业已上传成功！'
      })
      this.setState({ loading });
    }
    if (info.file.status === 'error') {
      loading[Number((i+1)+''+(j+1))] = false;
      this.setState({ loading });
      // _alert('上传失败，请重新上传!');
      Dialog({
        message: '上传失败，请重新上传!'
      })
    }
  }

  handlePlayer = (tableId, tableName) => () => {
    http.get('/student/course-table/getProgrammeUrl', { tableId }).then(res => {
      this.setState({
        mediaShow: true,
        mediaTitle: tableName,
        mediaUrl: res.data,
      })
    })
  }

  handleClose = () => {
    this.setState({
      mediaShow: false,
      mediaTitle: '',
      mediaUrl: ''
    })
  }

  download = downloadPath => () => {
    downloadByObjectKey(downloadPath)
  }
  handleGoScratch3 = () => {
    const scratchRef = window.open("", "_blank")
    setTimeout(() => {
      scratchRef.location = `http://scratch.zilongshu.com/`;
    }, 800);
  }
  prepareMaterial = (type, tableId) => () => {
    const showErrorNotice = true
    const winRef = window.open("", "_blank")
    http.get('/student/course-table/getMaterId', { tableId, type }).then(res => {
      // window.open(`/#/student_center_/material/${res.data}/${type}`)
      if(res.code == 1){
        setTimeout(() => {
          winRef.location = `/#/student_center_/material/${res.data}/${type}`
        }, 800);
      }else{
        Dialog({
          message: '题库尚未维护成功,请联系对应的课程顾问!'
        })
      }
    })
  }
  lookMore = courseId => () => {
    this.props.history.push('/student_center/my_courses/layout/more_course_material/'+courseId)
  }
  render() {
    const { tabsData, recordList, loading, mediaShow, mediaTitle, mediaUrl } = this.state
    return (
      <div className="recorded-course-list">
        <Tabs tabsData={tabsData} changeTab={this.changeTab} fontColor="#fff"/>
        <div className="recorded-course-list-content">
          {
            recordList.length > 0 ? recordList.map((record, i) => {
              const {
                allHour, // 总课时
                courseName, // 课程名称
                courseType, // 1-英语，3-编程
                downloadPath, // 素材下载地址
                level, // 级别
                levelDesc,
                pcUrl, // pc的封面
                platformType, // 2-Zoom/直播，3-录播
                studyCount, // 已学课时
                details=[], // 录播课的课表
                courseId,
              } = record
              return (
                <div className="recorded-item" key={i}>
                  <div className="item-header clearfloat">
                    <div className="img">
                      <img src={pcUrl} />
                      <i className={courseType === 1 ? 'english-icon' : 'program-icon'}></i>
                    </div>
                    <div className="header-right clearfloat">
                      <div className="title clearfloat">
                        <p>{courseName}</p>
                        {level == -1 ? null : <span>课程等级：{levelDesc}</span>}
                        
                      </div>
                      <ul className="recorded-content clearfloat">
                        <li>总课时：{allHour}课时</li>
                        <li>已学习：{studyCount}课时</li>
                        <li onClick={this.handleGoScratch3} className="hover-pointer"><Icon type="compass" /><span >在线编程</span></li>
                        <li onClick={this.download(downloadPath)} className="hover-pointer"><Icon type="download" /><span>素材下载</span></li>
                      </ul>
                      <div className="tips">
                        为保证学习效果，每周解锁2课时
                        ，查看往期课程资料，请 <a onClick={this.lookMore(courseId)}>点击此处</a>。
                      </div>
                    </div>
                  </div>
                  <ul className="item-content-recorded">
                    {
                      details.map((item, j) => {
                        const {
                          classUrl, // 视频Url
                          lesson, // 课程编号
                          status, // 1-未上课/开始学习，2-已上完/再学一遍
                          tableId, // 课表ID
                          tableName, // 课表名称
                        } = item
                        const len = details.length;
                        if(status === 2) {
                          return (
                            <li className="unfinished" key={j}>
                              <i className={len === j + 1 ? 'last' : ''}></i>
                              <span>Lesson {lesson}</span>
                              <span>{tableName}</span>
                              <span onClick={this.prepareMaterial(1, tableId)}><Icon type="laptop" /> 课程教材</span>
                              {/* <span><Icon type="upload" /> 任务上传</span> */}
                              <Upload
                                name="file"
                                style={{width: 120, marginLeft: 6}}
                                action={`/student/business/uploadCourseTask?tableId=${tableId}`}
                                showUploadList={false}
                                onChange={this.uploadCourseTask(i, j)}
                              >
                                <span className="span"><Icon type={loading[Number((i+1)+''+(j+1))] ? 'loading' : 'upload'} /><span>任务上传</span></span>
                              </Upload>
                              <span className="btn" onClick={this.handlePlayer(tableId, tableName)}>再学一遍</span>
                            </li>
                          )
                        }else if(status === 1) {
                          return (
                            <li className="completed" key={j}>
                              <i className={len === j + 1 ? 'last' : ''}></i>
                              <span>Lesson {lesson}</span>
                              <span>{tableName}</span>
                              <span onClick={this.prepareMaterial(1, tableId)}><Icon type="laptop" /> 课程教材</span>
                              <Upload
                                name="file"
                                style={{width: 120, marginLeft: 6}}
                                action={`/student/business/uploadCourseTask?tableId=${tableId}`}
                                showUploadList={false}
                                onChange={this.uploadCourseTask(i, j)}
                              >
                                <span className="span"><Icon type={loading[Number((i+1)+''+(j+1))] ? 'loading' : 'upload'} /><span>任务上传</span></span>
                              </Upload>
                              <span className="btn" onClick={this.handlePlayer(tableId, tableName)}>开始学习</span>
                            </li>
                          )
                        }
                      })
                    }
                  </ul>
                </div>
              )
            }) : <NoData />
          }
        </div>
        <MediaPlayer 
          show={mediaShow}
          src={mediaUrl}
          title={mediaTitle}
          onCancel={this.handleClose}
        />
      </div>
    )
  }
}